<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Utils\EncryptUtil;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class EncryptResponseMiddleware implements MiddlewareInterface
{
    /**
     * 处理响应
     *
     * @param ServerRequestInterface $request 请求对象
     * @param RequestHandlerInterface $handler 请求处理器
     * @return ResponseInterface 响应对象
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 先获取原始响应
        $response = $handler->handle($request);

        // 非正式环境不加密
        if (!is_prod()) {
            return $response;
        }

        // 获取原始响应内容
        $content      = $response->getBody()->getContents();
        $responseData = json_decode($content, true);
        if (!is_array($responseData)) {
            return $response;
        }

        // 加密响应数据
        $encryptedData = EncryptUtil::encrypt($responseData, get_device_identifier());

        // 重新设置响应内容
        return $response->withAddedHeader('content-type', 'text/html')
            ->withStatus(200)->withBody(new SwooleStream($encryptedData));
    }
} 